var hotkeyCode
var hotkeyShift
var hotkeyCtrl
var hotkeyAlt
var useCtrl
var ctrlPressed = false

$(document).ready(function() {
    chrome.extension.sendRequest({type: "gethotkey"}, function(response) {
        hotkeyCode = response.value
        hotkeyShift = (response.shift === "true")
        hotkeyCtrl = (response.ctrl === "true")
        hotkeyAlt = (response.alt === "true")
        useCtrl = (response.useCtrl === "true")
        if (useCtrl) {
//            alert("using ctrl")
            $(window).keydown(onCtrlDown)
            $(window).keyup(onCtrlUp)
        } else {
//            alert("not using ctrl")
            $(window).keydown(onHotKeyPressed)
        }
    })
    chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
        if (request.type == "sethotkey") {
            hotkeyCode = request.value
            hotkeyShift = (request.shift === "true")
            hotkeyCtrl = (request.ctrl === "true")
            hotkeyAlt = (request.alt === "true")
            useCtrl = (request.useCtrl === "true")
            $(window).unbind("keydown")
            $(window).unbind("keyup")
            if (useCtrl) {
                $(window).keydown(onCtrlDown)
                $(window).keyup(onCtrlUp)
//            alert("keydown event was rebound")
            } else {
                $(window).keydown(onHotKeyPressed)

            }
        }
    })
})

function onHotKeyPressed(event) {
    if (event.which < 48 || event.which > 90) return
//    alert(event.which + " " + event.shiftKey + " " + event.ctrlKey + " " + event.altKey + " " +
//            hotkeyCode + " " + hotkeyShift + " " + hotkeyCtrl + " " + hotkeyAlt)
    if (event.which == hotkeyCode && event.shiftKey == hotkeyShift &&
            event.ctrlKey == hotkeyCtrl && event.altKey == hotkeyAlt) {
        if (window.getSelection().toString().trim() == "") return
        chrome.extension.sendRequest({
            type: "translate",
            text: window.getSelection().toString()
        })
    }
}

function onCtrlDown(event) {
    if (event.which == 17) {
        ctrlPressed = true
    }
}

function onCtrlUp(event) {
    if (event.which == 17) {
        ctrlPressed = false
        if (window.getSelection().toString().trim() == "") return
        chrome.extension.sendRequest({
            type: "translate",
            text: window.getSelection().toString()
        })
    }
}